<template>
  <div>
    登录
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="120"
      :size="formSize"
      status-icon
    >
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="ruleForm.userName" />
      </el-form-item>
      <el-form-item label="密码" prop="passwordMd5">
        <el-input type="password" v-model="ruleForm.passwordMd5" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          登录
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import axios from "../ajax";
import { useRouter } from "vue-router";

import md5 from "md5";
const router = useRouter();

const formSize = ref("default");
const ruleFormRef = ref();
const ruleForm = reactive({
  userName: "admin",
  passwordMd5: "123456",
});

const rules = reactive({
  //验证
  userName: [
    { required: true, message: "输入用户名", trigger: "blur" },
    { min: 3, message: "用户名长度3-5", trigger: "blur" },
  ],
  passwordMd5: [{ required: true, message: "输入密码", trigger: "blur" }],
});

const submitForm = async (formEl) => {
  //提交
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      Login();
    } else {
      console.log("验证未通过");
    }
  });
};

const Login = async () => {
  //console.log("ajax")// 存token  跳转页面
  let { userName, passwordMd5 } = ruleForm;
  // console.log(userName, md5(passwordMd5));
  let res = await axios.post("/adminUser/login", {
    passwordMd5: md5(passwordMd5),
    userName,
  });
  // console.log(res);
  if (res) {
     localStorage.setItem("token",res)
    router.replace("/index");
  }else{

  }
};
</script>

<style>
</style>